require(["jquery",'public','weui'],function($,public,weui) {
    //public.headertitle('编辑信息');
    //public.footer(1);
    public.allocator();
    console.log(11)

    var cates = {
        1: '农副产品',
        2: '生产加工',
        3: '生活用品',
        4: '服装',
        5: '其他',
    };

    var pid = public.getUrlParam('id');

    var tmpl = '<div class="choose_img_item uploader_callback" style="background-image:url(#url#)"><a class="choose_img_item_delete" href="#"></a><input type="hidden" value="#url#" class="uploader_imgs"></div>';
    var $gallery = $("#gallery");
    var $galleryImg = $("#galleryImg");
    $(document).on("change",".weui-uploader__input", function(e){
        var $this = $(this);
        var $uploaderFiles = $this.parent().siblings('.choose_box');
        var length = $this.data('length') || 1;
        var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
        for (var i = 0, len = files.length; i < len; ++i) {
            var file = files[i];
            if(file.type.search(/image/) < 0){
                $.alert('请选择图片');
                return false;
            }
            if (url) {
                src = url.createObjectURL(file);
            } else {
                src = e.target.result;
            }
            $('.uploader_callback').removeClass('uploader_callback');
            $uploaderFiles.append($(tmpl.replace('#url#', src)));
            var $parent = $this.parent();
            uploader($this);
            if($uploaderFiles.find('.choose_img_item').size() >= length){
                $parent.hide();
                return false;
            }
        }
    });

    //获取产品详情
    function getData(id){
        $.ajax({
            type: 'post',
            dataType: 'json',
            data: {id:id, type: 1, token: public.getSession('token')},
            async: false,
            url: MODULE+'Goods/goods_info',           
        }).success(function (res) {
            console.log(res);
            if(res.code == 0){                
                $('[name="title"]').val(res.data.goods_name);
                $('[name="intor"]').val(res.data.goods_main);
                $('[name="price"]').val(res.data.goods_price);
                $('[name="shipping"]').val(res.data.goods_fare);
                $('.product_item_input_cate').addClass('bgnone').data('id',res.data.goods_cc_id).text(cates[res.data.goods_cc_id]);
                
                res.data_picture.forEach(function(i){
                    if(i.album_type == 1){
                        //轮播图banner
                        $('.product_list .choose_box').append($(tmpl.replace('#url#', PUBLIC+i.album_path).replace('#url#', i.album_path)));
                    }else{
                        //详情图detail
                        $('.product_list2 .choose_box').append($(tmpl.replace('#url#', PUBLIC+i.album_path).replace('#url#', i.album_path)));
                    }
                });
                
                if($('.product_list .choose_img_item').size() >= 3){
                    $('.product_list .weui-uploader__input-box').hide();
                }                
                
                if($('.product_list2 .choose_img_item').size() >= 3){
                    $('.product_list2 .weui-uploader__input-box').hide();
                }
            }else{
                $.alert(res.msg,function(){
                    window.history.go(-1);
                });
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {});
    }

    getData(pid);

    //页面加载完毕
    public.loaded();

    $('.choose_box').on('click','.choose_img_item_delete',function(event){
        event.preventDefault();
        event.stopPropagation();
        var $this = $(this);
        var index = $this.parent().index();
        $this.closest('.choose_box').siblings('.weui-uploader__input-box').show();
        $this.parent().remove();
    });

    $('.choose_box').on("click", ".choose_img_item", function(){
        $galleryImg.attr("style", this.getAttribute("style"));
        $gallery.fadeIn(100);
    });
    $gallery.on("click", function(){
        $gallery.fadeOut(100);
    });

    
    //上传文件
    var $form = $('#upload_form');
    function uploader($this){
        $this.after($this.clone());
        $form.empty().append($this).append('<input name="token" value="'+public.getSession('token')+'">').submit();
    }

    //上传回调
    $('#upload_frame_1').unbind("load").load(function() {
        var contents = $(this).contents().get(0);
        var data = $(contents).find('body').text();
        try{
            data = window.eval('(' + data + ')');
        }catch(e){
            if(data != ''){
                $.alert("上传失败");
            }
        }
        if(data == ''){
            $.confirm("你要离开本页么?", function() {
                window.history.go(-1);
            }, function() {
                //...
            });
            return false;
        }
        console.log(data);
        if(data.code == 0){
            $.alert("上传成功");
            $('.uploader_callback').find('.uploader_imgs').val(data.data);
        }else if(data.code == 1){
            $.alert("上传失败");
        }
    });

    //打开分类
    $('.product_main').on('click','.product_item_input_cate',function(event){
        event.preventDefault();
        if($(this).hasClass('on')){
            return false;
        }
        $(this).addClass('on');
        $('.product_cate').removeClass('hide');
        setTimeout(function(){
            $('.product_cate').addClass('show');
        },10);
    });

    //关闭分类
    $('.product_cate').on('click','.backAdd',function(event){
        event.preventDefault();
        event.stopPropagation();
        $('.product_cate').removeClass('show');
        setTimeout(function(){
            $('.product_item_input_cate').removeClass('on');
            $('.product_cate').addClass('hide');
        },400);
    });
    $('.product_cate').on('click',function(event){
        if($(event.target).hasClass('product_cate')){
            $('.backAdd').trigger('click');
        }
    });

    //选择分类
    $('.product_cate').on('click','.cate_item',function(event){
        event.preventDefault();
        event.stopPropagation();
        var id = $(this).data('id');
        var txt = $(this).text();
        $('.product_item_input_cate').addClass('bgnone').html(txt).attr('data-id',id);
        $('.backAdd').trigger('click');
    });

    //保存
    $('.save_box').on('click','.save',function(event){
        event.preventDefault();
        var banner_img = [];
        $('.product_list .uploader_imgs').each(function(){
            banner_img.push($(this).val());
        });
        var detail_img = [];
        $('.product_list2 .uploader_imgs').each(function(){
            detail_img.push($(this).val());
        });
        var data = {
            token: public.getSession('token'),
            id: pid,
            title: $('[name="title"]').val(),
            intor: $('[name="intor"]').val(),
            price: $('[name="price"]').val(),
            shipping: $('[name="shipping"]').val(),
            cate_id: $('.product_item_input_cate').data('id'),
            cate: $('.product_item_input_cate').text(),
            banner: banner_img,
            detail: detail_img,
            type: 1,
        };
        if(data.title.trim() == ''){
            $.alert('请填写标题');
            return false;
        }
        if(data.intor.trim() == ''){
            $.alert('请填写描述');
            return false;
        }
        if(isNaN(data.price) || data.price < 0 || data.price.trim() == ''){
            $.alert('请填写价格');
            return false;
        }
        /*if(isNaN(data.shipping) || data.shipping < 0 || data.shipping.trim() == ''){
            $.alert('请填写运费');
            return false;
        }*/
        if(!data.cate_id){
            $.alert('请选择分类');
            return false;
        }
        if(!banner_img.length){
            $.alert('请上传产品图');
            return false;
        }
        $.ajax({
            type: 'post',
            data: data,
            dataType: 'json',
            url: MODULE+'Goods/goods',           
        }).success(function (res) {
            console.log(res); 
            if(res.code == 0){
                $.alert('保存成功',function(){
                    window.location.replace(MODULE+'PublicJump/myRelease');
                });
            }else{
                $.alert(res.info);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {});
    });
})